﻿using Calligraphy.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;

namespace CalligraphyWeb.Controllers
{
    public class ItemController : Controller
    {
        public ActionResult Delete(int id)
        {
            if (id <= 0)
                RedirectToAction("Manage", "Account", new { tab = "projects" });

            var temp = new Item(id, false);
            var result = temp.Delete();
            if (result > 0)
                RedirectToAction("Manage", "Account", new { tab = "projects" });

            return View("Manage");
        }

        public void ExportItem(int id)
        {

            var temp = new Item(id, false);

            var tmpl = temp.ToStoredItem();
            var xmlSerializer = new XmlSerializer(typeof(ThuPhap.Models.StoredItem));
            MemoryStream stream = new MemoryStream();
            xmlSerializer.Serialize(stream, tmpl);

            if (stream != null)
            {
                byte[] bytesInStream = stream.ToArray(); // simpler way of converting to array
                stream.Close();

                Response.Clear();
                Response.ContentType = "application/force-download";
                Response.AddHeader("content-disposition", "attachment;    filename=" + temp.Data.name + ".tp");
                Response.BinaryWrite(bytesInStream);
                Response.End();

            }
        }
    }
}
